<template>
  <div class="system-status">
    <div class="page-header">
      <h1>系统状态监控</h1>
      <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
        刷新数据
      </el-button>
    </div>

    <!-- 系统概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card class="status-card healthy">
          <div class="card-content">
            <el-icon class="card-icon"><SuccessFilled /></el-icon>
            <div class="card-info">
              <div class="card-value">{{ systemData.services?.microservices ? Object.keys(systemData.services.microservices).length : 0 }}</div>
              <div class="card-label">运行中的服务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="card-content">
            <el-icon class="card-icon"><Clock /></el-icon>
            <div class="card-info">
              <div class="card-value">{{ formatUptime(systemData.uptime) }}</div>
              <div class="card-label">系统运行时间</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="card-content">
            <el-icon class="card-icon"><Monitor /></el-icon>
            <div class="card-info">
              <div class="card-value">{{ systemData.services?.backend?.memory?.used || 0 }} MB</div>
              <div class="card-label">内存使用</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="card-content">
            <el-icon class="card-icon"><DataAnalysis /></el-icon>
            <div class="card-info">
              <div class="card-value">{{ systemData.version }}</div>
              <div class="card-label">系统版本</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 微服务状态 -->
    <el-card class="services-card">
      <template #header>
        <div class="card-header">
          <span>微服务状态</span>
          <el-tag type="success">全部运行中</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8" v-for="(service, name) in systemData.services?.microservices" :key="name">
          <div class="service-item">
            <div class="service-header">
              <el-icon class="service-icon" :class="{ 'running': service.status === 'running' }">
                <CircleCheckFilled v-if="service.status === 'running'" />
                <CircleCloseFilled v-else />
              </el-icon>
              <div class="service-info">
                <div class="service-name">{{ name }}</div>
                <div class="service-port">端口: {{ service.port }}</div>
              </div>
            </div>
            <el-tag :type="service.status === 'running' ? 'success' : 'danger'" size="small">
              {{ service.status }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 性能指标 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>性能指标</span>
          </template>
          <div class="metrics-grid">
            <div class="metric-item">
              <div class="metric-label">请求/秒</div>
              <div class="metric-value">{{ metricsData.performance?.requestsPerSecond || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">平均响应时间</div>
              <div class="metric-value">{{ metricsData.performance?.avgResponseTime || 0 }} ms</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">P95响应时间</div>
              <div class="metric-value">{{ metricsData.performance?.p95ResponseTime || 0 }} ms</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">错误率</div>
              <div class="metric-value">{{ metricsData.performance?.errorRate || 0 }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>业务指标</span>
          </template>
          <div class="metrics-grid">
            <div class="metric-item">
              <div class="metric-label">活跃告警</div>
              <div class="metric-value">{{ metricsData.business?.alerts?.pending || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">已处理告警</div>
              <div class="metric-value">{{ metricsData.business?.alerts?.processed || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">创建工单</div>
              <div class="metric-value">{{ metricsData.business?.tickets?.created || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">已解决工单</div>
              <div class="metric-value">{{ metricsData.business?.tickets?.resolved || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据库状态 -->
    <el-card class="database-card">
      <template #header>
        <span>数据库状态</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="database-item">
            <el-icon class="db-icon mongodb"><Database /></el-icon>
            <div class="db-info">
              <div class="db-name">MongoDB</div>
              <div class="db-status">
                <el-tag type="success" size="small">{{ systemData.services?.database?.mongodb?.status }}</el-tag>
                <span class="db-latency">延迟: {{ systemData.services?.database?.mongodb?.latency }}ms</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="database-item">
            <el-icon class="db-icon redis"><Coin /></el-icon>
            <div class="db-info">
              <div class="db-name">Redis</div>
              <div class="db-status">
                <el-tag type="success" size="small">{{ systemData.services?.database?.redis?.status }}</el-tag>
                <span class="db-latency">延迟: {{ systemData.services?.database?.redis?.latency }}ms</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 系统日志 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>最近系统日志</span>
          <el-button text @click="viewAllLogs">查看全部</el-button>
        </div>
      </template>
      <el-table :data="logsData.logs" style="width: 100%">
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLogLevelType(row.level)" size="small">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="service" label="服务" width="150" />
        <el-table-column prop="message" label="消息" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  SuccessFilled,
  Clock,
  Monitor,
  DataAnalysis,
  CircleCheckFilled,
  CircleCloseFilled,
  Database,
  Coin
} from '@element-plus/icons-vue'
import axios from 'axios'

const loading = ref(false)
const systemData = ref<any>({})
const metricsData = ref<any>({})
const logsData = ref<any>({ logs: [] })

const formatUptime = (seconds: number) => {
  if (!seconds) return '0h 0m'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}h ${minutes}m`
}

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const getLogLevelType = (level: string) => {
  const types: Record<string, any> = {
    info: 'info',
    warn: 'warning',
    error: 'danger'
  }
  return types[level] || 'info'
}

const fetchSystemStatus = async () => {
  try {
    const response = await axios.get('http://localhost:8000/api/system/status')
    systemData.value = response.data.data
  } catch (error) {
    console.error('Failed to fetch system status:', error)
    ElMessage.error('获取系统状态失败')
  }
}

const fetchMetrics = async () => {
  try {
    const response = await axios.get('http://localhost:8000/api/system/metrics')
    metricsData.value = response.data.data
  } catch (error) {
    console.error('Failed to fetch metrics:', error)
  }
}

const fetchLogs = async () => {
  try {
    const response = await axios.get('http://localhost:8000/api/system/logs?limit=10')
    logsData.value = response.data.data
  } catch (error) {
    console.error('Failed to fetch logs:', error)
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchSystemStatus(),
      fetchMetrics(),
      fetchLogs()
    ])
    ElMessage.success('数据已刷新')
  } finally {
    loading.value = false
  }
}

const viewAllLogs = () => {
  ElMessage.info('查看全部日志功能开发中')
}

onMounted(() => {
  refreshData()
  // 每30秒自动刷新
  setInterval(refreshData, 30000)
})
</script>

<style scoped lang="scss">
.system-status {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }
  }

  .overview-cards {
    margin-bottom: 20px;

    .status-card {
      &.healthy {
        border-left: 4px solid #67c23a;
      }

      .card-content {
        display: flex;
        align-items: center;
        gap: 15px;

        .card-icon {
          font-size: 40px;
          color: #409eff;
        }

        .card-info {
          flex: 1;

          .card-value {
            font-size: 28px;
            font-weight: 600;
            color: #303133;
          }

          .card-label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }

  .services-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .service-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      margin-bottom: 10px;

      .service-header {
        display: flex;
        align-items: center;
        gap: 10px;

        .service-icon {
          font-size: 24px;
          color: #67c23a;

          &.running {
            color: #67c23a;
          }
        }

        .service-info {
          .service-name {
            font-weight: 600;
            font-size: 14px;
          }

          .service-port {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }

  .metrics-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;

    .metric-item {
      text-align: center;
      padding: 15px;
      background: #f5f7fa;
      border-radius: 4px;

      .metric-label {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .metric-value {
        font-size: 24px;
        font-weight: 600;
        color: #409eff;
      }
    }
  }

  .database-card {
    margin: 20px 0;

    .database-item {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 15px;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      .db-icon {
        font-size: 40px;

        &.mongodb {
          color: #47a248;
        }

        &.redis {
          color: #dc382d;
        }
      }

      .db-info {
        flex: 1;

        .db-name {
          font-size: 16px;
          font-weight: 600;
          margin-bottom: 8px;
        }

        .db-status {
          display: flex;
          align-items: center;
          gap: 10px;

          .db-latency {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}
</style>
